package cn.iocoder.yudao.module.system.service.useractivity;

import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.common.util.servlet.ServletUtils;
import cn.iocoder.yudao.module.system.event.UserActivityEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 用户活动记录服务实现类
 * 
 * @author 系统开发团队
 */
@Service
@Slf4j
public class UserActivityRecordServiceImpl implements UserActivityRecordService {

    @Resource
    private ApplicationEventPublisher eventPublisher;

    @Override
    public void recordLoginActivity(Long userId, String username, Integer userType, 
                                  String clientIp, String userAgent, Integer deviceType) {
        try {
            UserActivityEvent event = new UserActivityEvent(this, userId, username, userType, 
                                                           UserActivityEvent.ActivityType.LOGIN, "用户登录");
            event.setClientIp(clientIp);
            event.setUserAgent(userAgent);
            event.setDeviceType(deviceType != null ? deviceType : getDeviceTypeFromUserAgent(userAgent));
            
            publishUserActivityEvent(event);
            
            log.debug("[recordLoginActivity] 记录用户登录活动: userId={}, username={}", userId, username);
        } catch (Exception e) {
            log.error("[recordLoginActivity] 记录用户登录活动失败: userId={}, username={}", userId, username, e);
        }
    }

    @Override
    public void recordPageViewActivity(Long userId, String username, Integer userType, 
                                     String requestUri, String clientIp, String userAgent, Integer deviceType) {
        try {
            UserActivityEvent event = new UserActivityEvent(this, userId, username, userType, 
                                                           UserActivityEvent.ActivityType.PAGE_VIEW, "页面访问: " + requestUri);
            event.setClientIp(clientIp);
            event.setUserAgent(userAgent);
            event.setDeviceType(deviceType != null ? deviceType : getDeviceTypeFromUserAgent(userAgent));
            event.setRequestUri(requestUri);
            
            publishUserActivityEvent(event);
            
            log.debug("[recordPageViewActivity] 记录页面访问活动: userId={}, uri={}", userId, requestUri);
        } catch (Exception e) {
            log.error("[recordPageViewActivity] 记录页面访问活动失败: userId={}, uri={}", userId, requestUri, e);
        }
    }

    @Override
    public void recordApiCallActivity(Long userId, String username, Integer userType, 
                                    String requestUri, String requestMethod, 
                                    String clientIp, String userAgent, Integer deviceType) {
        try {
            UserActivityEvent event = new UserActivityEvent(this, userId, username, userType, 
                                                           UserActivityEvent.ActivityType.API_CALL, 
                                                           "API调用: " + requestMethod + " " + requestUri);
            event.setClientIp(clientIp);
            event.setUserAgent(userAgent);
            event.setDeviceType(deviceType != null ? deviceType : getDeviceTypeFromUserAgent(userAgent));
            event.setRequestUri(requestUri);
            event.setRequestMethod(requestMethod);
            
            publishUserActivityEvent(event);
            
            log.debug("[recordApiCallActivity] 记录API调用活动: userId={}, method={}, uri={}", userId, requestMethod, requestUri);
        } catch (Exception e) {
            log.error("[recordApiCallActivity] 记录API调用活动失败: userId={}, method={}, uri={}", userId, requestMethod, requestUri, e);
        }
    }

    @Override
    public void recordFeatureUseActivity(Long userId, String username, Integer userType, 
                                       String featureName, String clientIp, String userAgent, Integer deviceType) {
        try {
            UserActivityEvent event = new UserActivityEvent(this, userId, username, userType, 
                                                           UserActivityEvent.ActivityType.FEATURE_USE, 
                                                           "功能使用: " + featureName);
            event.setClientIp(clientIp);
            event.setUserAgent(userAgent);
            event.setDeviceType(deviceType != null ? deviceType : getDeviceTypeFromUserAgent(userAgent));
            
            publishUserActivityEvent(event);
            
            log.debug("[recordFeatureUseActivity] 记录功能使用活动: userId={}, feature={}", userId, featureName);
        } catch (Exception e) {
            log.error("[recordFeatureUseActivity] 记录功能使用活动失败: userId={}, feature={}", userId, featureName, e);
        }
    }

    @Override
    public void publishUserActivityEvent(UserActivityEvent event) {
        try {
            eventPublisher.publishEvent(event);
        } catch (Exception e) {
            log.error("[publishUserActivityEvent] 发布用户活动事件失败: userId={}, activityType={}", 
                     event.getUserId(), event.getActivityType(), e);
        }
    }

    @Override
    public Integer getDeviceTypeFromUserAgent(String userAgent) {
        if (StrUtil.isBlank(userAgent)) {
            return UserActivityEvent.DeviceType.WEB;
        }
        
        userAgent = userAgent.toLowerCase();
        
        // 检查是否为移动设备
        if (userAgent.contains("mobile") || userAgent.contains("android") || 
            userAgent.contains("iphone") || userAgent.contains("ipad") || 
            userAgent.contains("blackberry") || userAgent.contains("windows phone")) {
            return UserActivityEvent.DeviceType.MOBILE;
        }
        
        // 检查是否为桌面应用
        if (userAgent.contains("electron") || userAgent.contains("desktop")) {
            return UserActivityEvent.DeviceType.PC;
        }
        
        // 默认为Web
        return UserActivityEvent.DeviceType.WEB;
    }
}